package com.doge.calcalbum.business.note

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.doge.calcalbum.core.base.adapters.BaseAdapter
import com.doge.calcalbum.db.model.Note

class NoteAdapter : BaseAdapter() {
    private val dataList = mutableListOf<Note>()
    private val selectedIds = mutableListOf<Int>()
    private var isEditMode = false
    val selected get() = dataList.filter { selectedIds.contains(it.id) }

    fun submitList(data: List<Note>) {
        val result = data.map {
            it.copy(
                selected = when {
                    !isEditMode -> null
                    selectedIds.contains(it.id) -> true
                    else -> false
                }
            )
        }
        dataList.clear()
        dataList.addAll(result)
        notifyDataSetChanged()
    }

    fun exitEdit() {
        isEditMode = false
        selectedIds.clear()
        submitList(dataList)
    }

    fun enterEdit(data: Note? = null) {
        isEditMode = true
        if (data != null && !selectedIds.contains(data.id)) {
            selectedIds.add(data.id)
        }
        submitList(dataList)
    }

    fun switch(data: Note?) {
        if (data == null) return
        if (!selectedIds.contains(data.id)) selectedIds.add(data.id)
        else selectedIds.remove(data.id)
        submitList(dataList)
    }

    fun switchAll() {
        if (selectedIds.size == dataList.size) {
            selectedIds.clear()
        } else {
            selectedIds.clear()
            selectedIds.addAll(dataList.map { it.id })
        }
        submitList(dataList)
    }

    override fun getItemCount(): Int = dataList.size
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemType.Note -> NoteViewHolder(parent, callback)
            else -> super.onCreateViewHolder(parent, viewType)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val item = if (position < dataList.size) dataList[position] else null
        when (holder) {
            is NoteViewHolder -> item?.let { holder.bind(it) }
        }
    }

    override fun getItemViewType(position: Int): Int {
        if (position < 0 || position > dataList.size) return com.doge.calcalbum.core.base.adapters.ItemType.Unknown
        return ItemType.Note
    }
}
